/*
 * @Author: gitee_com_zb
 * @Date: 2024-11-28 17:28:38
 * @LastEditors: gitee_com_zb
 * @LastEditTime: 2024-11-28 17:28:41
 * @FilePath: /algorithm/每日一题3.合并k个已排序的链表(hard).cpp
 * @Description: 题目链接 https://www.nowcoder.com/share/jump/3018661641732786086221
 */
/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */

#include <queue>
class Solution {
public:
    struct greater {
        bool operator()(const ListNode* l1, const ListNode* l2) {
            return l1->val > l2->val;
        }
    };
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        // 简单思路:由于各个链表有序,每次选出多个链表头结点中的最小值,依次链接即可
        // 用一个小堆来选择多个链表中较小的头结点(或者放入一个数组,自己用算法去找出最小的结点)
        std::priority_queue<ListNode*, vector<ListNode*>, greater> heap;
        for(auto& l : lists) if(l) heap.push(l);
        ListNode* head = new ListNode(0);
        ListNode* resultList = head;
        while(!heap.empty()) {
            ListNode* minNode = heap.top();
            heap.pop();
            resultList->next = minNode;
            resultList = minNode;
            if(minNode->next) heap.push(minNode->next);
        }
        resultList = head->next;
        delete head;
        return resultList;
    }
};
